package cn.zwxky.android.staff.HomePage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.Event.LsfbEvent;
import com.zgscwjm.lsfbbasetemplate.LsfbFragment;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInjectUtils;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.utils.SPUtils;
import com.zgscwjm.lsfbbasetemplate.utils.T;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import cn.zwxky.android.staff.My.NewsCountBean;
import cn.zwxky.android.staff.My.NewsCountEvent2;
import cn.zwxky.android.staff.R;
import cn.zwxky.android.staff.Utils.LittleUtils;
import cn.zwxky.android.staff.Utils.NoDoubleClickUtils;
import cn.zwxky.android.staff.Utils.Permission;
import cn.zwxky.android.staff.Utils.PopWindowManager;
import cn.zwxky.android.staff.Utils.URLString;
import cn.zwxky.android.staff.Utils.WaveView;
import cn.zwxky.android.staff.Utils.WebActivity;


/**
 * Created by Administrator on 2017/3/21 0021.
 */

public class HomePageFragment extends LsfbFragment {

    /**
     * view 对象
     */
    private View view;

    /**
     * activity对象
     */
    private Activity mactivity;

    @ViewInject(R.id.fg_homepage_text_save)
    private TextView text_save;

    /**
     * 定位信息
     */
    @ViewInject(R.id.fg_homepage_text_content)
    private TextView text_content;

    @ViewInject(R.id.wave_view)
    private WaveView mWaveView;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    private LocationDBHelper dbHelper;

    /**
     * PopWindow管理类
     */
    private PopWindowManager replay;

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1000:
                    text_content.setText("北纬" + LittleUtils.address_weidu + "    东经" + LittleUtils.address_jindu);
                    break;
                case 2000:
                    mWaveView.stop();
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_homepage, null);
        ViewInjectUtils.inject(this, view);
        LsfbEvent.getInstantiation().register2(this);

        Permission permission = new Permission(mactivity);
        permission.GetMeshPermission();
        permission.GetAddressBookPermission();
        permission.GetLocationPermission2();
        mLocationClient = new LocationClient(mactivity.getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        initLocation();
        mLocationClient.start();

        //创建StuDBHelper对象
        dbHelper = new LocationDBHelper(mactivity);
        getAltitude();
        if (SPUtils.get(mactivity, "fast", "0").equals("0")) {
            dbHelper.insert("0", "0", "0", "");
            SPUtils.put(mactivity, "fast", "1");
        }

        getNumber();
        return view;
    }

    private SensorManager sensorManager = null;
    private Sensor mPressure;

    public void getAltitude() {
        sensorManager = (SensorManager) mactivity.getSystemService(Context.SENSOR_SERVICE);
        mPressure = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        if (mPressure == null) {
            T.showShort(mactivity, "您的手机不支持气压传感器，无法查看海拔信息");
            return;

        }
//        mPressure = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    SensorEventListener pressureListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            float sPV = event.values[0];
            DecimalFormat df = new DecimalFormat("0.00");
            df.getRoundingMode();
            // 计算海拔
            double height = 44330000 * (1 - (Math.pow((Double.parseDouble(df.format(sPV)) / 1013.25),
                    (float) 1.0 / 5255.0)));
            LittleUtils.address_haiba = df.format(height);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub

        }
    };

    /**
     * 用于存储activity对象
     *
     * @param activity
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mactivity = activity;
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.fg_home_list, R.id.fg_qiandao, R.id.fg_homepage_img_dingwei, R.id.fg_homepage_text_save, R.id.big_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            //已存列表
            case R.id.fg_home_list:
                startActivity(new Intent(mactivity, LocationActivity.class));
                break;
            //签到
            case R.id.fg_qiandao:
                startActivity(new Intent(mactivity, FootprintActivity.class));
                break;
            //定位
            case R.id.fg_homepage_img_dingwei:
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    mLocationClient.start();
                    T.showShort(mactivity, "定位中...");
                }
                break;
            //保存
            case R.id.fg_homepage_text_save:
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                if (LittleUtils.address_jindu.isEmpty() || LittleUtils.address_weidu.isEmpty()) {
                    SN.SnackShow(text_save, "没有定位信息可保存");
                    return;
                }
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    dbHelper.insert(LittleUtils.address_jindu, LittleUtils.address_weidu, LittleUtils.address_haiba, str);
                    SN.SnackShow(text_save, "定位信息保存成功");
                }
                break;
            case R.id.big_btn:
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    mLocationClient.start();
                    T.showShort(mactivity, "定位中...");
                }
                getAltitude();
                mWaveView.setInitialRadius(250);
                mWaveView.setDuration(2000);
                mWaveView.setStyle(Paint.Style.FILL);
                mWaveView.setColor(Color.parseColor("#525f8c"));
                mWaveView.setInterpolator(new LinearOutSlowInInterpolator());
                mWaveView.start();
                handler.sendEmptyMessageDelayed(2000, 2000);
                break;
        }
    }

    @Override
    protected void Resume() {
        sensorManager.registerListener(pressureListener, mPressure,
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (pressureListener != null) {
            sensorManager.unregisterListener(pressureListener);
        }
    }

    @Override
    public void initData() {

    }

    /**
     * 百度定位设置
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        if (LittleUtils.isNetworkAvailable(mactivity)) {
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        } else {
            option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
        }
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }


    /**
     * 定位回调
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            //获取定位结果
            StringBuffer sb = new StringBuffer(256);
            location.getLocType();
            LsfbLog.e("百度错误代码" + location.getLocType());
            double jindu = location.getLongitude();
            double weidu = location.getLatitude();
//            double haiba = location.getAltitude();
            String address = location.getAddrStr();
            if (location.getLocType() == BDLocation.TypeGpsLocation) {

//                if (haiba == 4.9E-324) {
//                    haiba = location.getAltitude();
//                }
                if (address == null) {
                    address = location.getAddrStr();    //获取地址信息
                }
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
//                if (haiba == 4.9E-324) {
//                    haiba = location.getAltitude();
//                }
                if (address == null) {
                    address = location.getAddrStr();    //获取地址信息
                }
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");

            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
//                if (haiba == 4.9E-324) {
//                    haiba = location.getAltitude();
//                }
                if (address == null) {
                    address = location.getAddrStr();    //获取地址信息
                }
                // 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");

            } else if (location.getLocType() == BDLocation.TypeServerError) {
//                T.showShort(mactivity, "服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");

            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                T.showShort(mactivity, "网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                T.showShort(mactivity, "无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
//            if (haiba == 1.01) {
//                T.showShort(mactivity, "海拔高度定位失败，请开启手机GPS功能");
//            }
//
//            if (haiba != 4.9E-324) {
//                LittleUtils.address_haiba = LittleUtils.m2(haiba);
//            }

            LittleUtils.address = address;

            if (jindu != 4.9E-324) {
                LittleUtils.address_jindu = LittleUtils.DDtoDMS(jindu);
                LittleUtils.address_weidu = LittleUtils.DDtoDMS(weidu);
                handler.sendEmptyMessage(1000);
                T.showShort(mactivity, "定位成功");
                mLocationClient.stop();
            }
            LsfbLog.e("lalal" + jindu);
            LsfbLog.e("lalal" + weidu);
            LsfbLog.e("lalal" + address);
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    }


    /**
     * 获取公司公告新闻条数
     */
    public void getNumber() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("uid", Config.getUserId());
        new BaseInternet().getData_Get(URLString.NEWSCOUNT, hashMap, NewsCountBean.class, new NewsCountEvent2<NewsCountBean>(), true, true);
    }

    @EventAnnotation
    public void NewsCountEvent(final NewsCountEvent2<NewsCountBean> event) {
        switch (event.getCode()) {
            case 200:
                if (!event.getData().getCount().equals("0")) {
                    replay = new PopWindowManager(mactivity, R.layout.pop_notice) {
                        @Override
                        public void onViewLister(View contentView, final PopWindowManager manager) {

                            final TextView pop_exit_exit = (TextView) contentView.findViewById(R.id.pop_exit_exit);
                            final TextView pop_exit_look = (TextView) contentView.findViewById(R.id.pop_exit_look);
                            final TextView pop_text_notice = (TextView) contentView.findViewById(R.id.pop_text_notice);
                            final RelativeLayout RelativeLayout = (RelativeLayout) contentView.findViewById(R.id.RelativeLayout);

                            pop_text_notice.setText(event.getData().getList().get(0).getTitle());

                            //退出
                            pop_exit_exit.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    manager.hideWindow();
                                }
                            });

                            //查看
                            pop_exit_look.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    startActivity(new Intent(mactivity, WebActivity.class).putExtra("url", URLString.WED_URL + event.getData().getList().get(0).getUrl() + Config.getUserId()).putExtra("title", "查看全文"));
                                    manager.hideWindow();
                                }
                            });

                            RelativeLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    manager.hideWindow();
                                }
                            });

                        }
                    };
                    replay.showWindowsCenter(mactivity.getWindow().getDecorView());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        LsfbEvent.getInstantiation().unregister2(this);
        super.onDestroy();
    }


}
